package com.changgou.search.searchController;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.searchService.SearchService;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * @version v1.0
 * @ProjectName: changgou_parent
 * @ClassName: SearchController
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Xu Fj
 * @Date: 2020/3/1 15:35
 */
@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String search(@RequestParam Map<String,String> paramMap, Model model) throws Exception {
        handlerSearchMap(paramMap);
        Map resultMap = searchService.search(paramMap);
        model.addAttribute("searchMap",paramMap);
        model.addAttribute("resultMap",resultMap);

        //封装分页数据并返回
        long total = Long.parseLong(String.valueOf(resultMap.get("total")));  //总条数
        int pageNum = Integer.parseInt(String.valueOf(resultMap.get("pageNum"))); //总页数
        Page<SkuInfo> page = new Page<>(total,pageNum,Page.pageSize); //每页显示条数
        model.addAttribute("page",page);

        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if (paramMap != null &&paramMap.size()>0){
            url.append("?");
            for (String paramKey : paramMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(paramMap.get(paramKey)).append("&");
                }
            }

            String urlString = url.toString();
            //截取
            urlString = urlString.substring(0,urlString.length()-1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }
        return "search";
    }


    @GetMapping
    @ResponseBody
    public Map search(Map<String,String> paramMap) throws Exception {
        handlerSearchMap(paramMap);
        Map searchMap = searchService.search(paramMap);
        return searchMap;
    }

    private void handlerSearchMap(Map<String, String> paramMap) {
        if (paramMap!=null){
            Set<Map.Entry<String, String>> entries = paramMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")){
                    paramMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
        }
    }

}
